package com.ruoyi.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.ruoyi.common.core.domain.AmountDto;
import com.ruoyi.common.core.domain.Range;

import java.math.BigDecimal;
import java.util.List;
import java.util.function.Function;

public class AmountUtil {
    public static BigDecimal getAmountByCurrency(String amountJsonArray, String currency) {
        List<AmountDto> amountDtos = JSONArray.parseArray(amountJsonArray, AmountDto.class);
        for (AmountDto amountDto : amountDtos) {
            if (amountDto.getCurrency().equals(currency)) {
                return amountDto.getAmount();
            }
        }

        return BigDecimal.ZERO;
    }

    /**
     * 获取列表的最小与最大值
     * @param list 对象列表
     * @param covert 转换函数
     * @param <T> 对象类型
     * @param <R> 转换结果类型
     * @return 返回区间
     */
    public static <T, R extends Number & Comparable<R>> Range<R> findMinMaxRange(List<T> list, Function<T, R> covert) {
        AssertUtils.notNull(list, "list must not be null");
        R min, max;
        min = max = covert.apply(list.get(0));
        if (min == null) return null;
        for (T t : list) {
            R r = covert.apply(t);
            if (r == null) {
                continue;
            }
            if (min.compareTo(r) > 0) {
                min = r;
            }
            if (max.compareTo(r) < 0) {
                max = r;
            }
        }
        return new Range<>(min, max);
    }

}
